//
//  RefreshFooter.swift
//  CodingTest
//
//  Created by LYPC on 2021/11/18.
//

import UIKit
import SnapKit
import MJRefresh

final class CTRefreshFooter: MJRefreshAutoFooter {
    
    private lazy var loading: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView()
        if #available(iOS 13.0, *) {
            indicator.style = .medium
        } else {
            indicator.style = .white
        }
        indicator.color = .gray
        indicator.hidesWhenStopped = true
        self.addSubview(indicator)
        return indicator
    }()
    
    private var noMoreLabel: UILabel!
    private var noMoreLineView: UIView!
    
    public func setNoMoreTitle(_ attrStr: NSAttributedString) {
        noMoreLabel.attributedText = attrStr
    }
    
    override func prepare() {
        super.prepare()
        
        self.mj_h = 50
        
        noMoreLabel = UILabel()
        noMoreLabel.backgroundColor = UIColor.clear
        noMoreLabel.textAlignment = .center
        noMoreLabel.isHidden = true
        self.addSubview(noMoreLabel)
    }
    
    // MARK: - ********* 在这里设置子控件的位置和尺寸
    override func placeSubviews() {
        super.placeSubviews()
        noMoreLabel.frame = self.bounds
        loading.center = CGPoint.init(x: self.mj_w * 0.5, y: self.mj_h * 0.5)
    }
    
    override var state: MJRefreshState {
        get {
            return super.state
        }
        set(newState) {
            if newState == state {
                return
            }
            super.state = newState
            switch state {
            case .idle:
                noMoreLabel.isHidden = true
                loading.hidesWhenStopped = true
                loading.stopAnimating()
            case .pulling:
                loading.hidesWhenStopped = false
                loading.stopAnimating()
            case .refreshing:
                loading.hidesWhenStopped = false
                loading.startAnimating()
            case .noMoreData:
                noMoreLabel.isHidden = false
                loading.hidesWhenStopped = true
                loading.stopAnimating()
            default:
                break
            }
        }
    }
}

